package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckItemICheckGroupIdMapper;
import com.itheima.mapper.CheckgroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckgroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class CheckgroupServiceImpl implements CheckgroupService {
    @Autowired
    private CheckgroupMapper checkgroupMapper;
    @Autowired
    private CheckItemICheckGroupIdMapper checkItemICheckGroupIdMapper;

    //条件分页查询
    public PageResult findPage(QueryPageBean queryPage) {
        //设置分页参数
        PageHelper.startPage(queryPage.getCurrentPage(), queryPage.getPageSize());
        //调用数据库查询
        Page<CheckGroup> page = (Page<CheckGroup>) checkgroupMapper.findPage(queryPage);

        return new PageResult(page.getTotal(), page.getResult());
    }

    //添加检查组 中间关系表新增
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //添加检查组
        checkgroupMapper.add(checkGroup);
        //添加中间表
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                checkItemICheckGroupIdMapper.addCheckGroupAndCheckItem(checkGroup.getId(), checkitemId);
            }
        }
    }

    //根据id查询检查组


    @Override
    public CheckGroup findById(Integer id) {

        return checkgroupMapper.findById(id);
    }

    //编辑检查组
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改检查组
        checkgroupMapper.edit(checkGroup);
        //删除中间表
        checkItemICheckGroupIdMapper.delete(checkGroup.getId());
        //添加中间表
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                checkItemICheckGroupIdMapper.addCheckGroupAndCheckItem(checkGroup.getId(), checkitemId);
            }
        }
    }

    //查询所有检查组
    public List<CheckGroup> findAll() {
        return checkgroupMapper.findAll();
    }

    //根据id删除检查组
    public void delete(Integer id) {
        //删除中间表
        checkItemICheckGroupIdMapper.delete(id);
        //删除检查组
        checkgroupMapper.delete(id);
    }

    //根据套餐id查询检查组
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return checkgroupMapper.findCheckGroupIdsBySetmealId(setmealId);
    }
}
